<template>
    <div class="app-container">
        <el-row>
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                <el-form-item label="渠道号" prop="channelId">
                    <el-input
                        v-model="queryParams.channelId" placeholder="请输入渠道号" clearable style="width: 180px"
                        @keyup.enter="handleSearch"/>
                </el-form-item>
                <el-form-item label="渠道名称" prop="channelName">
                    <el-input
                        v-model="queryParams.channelName" placeholder="请输入渠道名称" clearable style="width: 180px"
                        @keyup.enter="handleSearch"/>
                </el-form-item>
                <el-form-item label="运营商" prop="isp">
                    <el-select
                        v-model="queryParams.isp"
                        :empty-values="[null, undefined]"
                        :value-on-clear="null"
                        clearable
                        placeholder="请选择运营商"
                        style="width: 200px"
                    >
                        <el-option
                            v-for="item in ispOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button icon="Refresh" @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="Plus" plain @click="handleCreate"
                           v-permission="['sys.plat.channel.create']">新增
                </el-button>
            </el-col>
        </el-row>
        <el-table v-loading="tableLoading" :data="tableData" row-key="id" stripe>
            <el-table-column type="expand" fixed="left">
                <template #default="scope">
                    <el-row class="areaName-row" :gutter="5">
                        {{ scope.row.areaName }}
                    </el-row>
                </template>
            </el-table-column>
            <template v-for="(item, idx) in columns" :key="idx">
                <el-table-column :prop="item.prop" :label="item.label" :fixed="item.fixed" v-if="item.show"
                                 :show-overflow-tooltip="true" :align="item.align" :width="item.width"
                                 :sortable="item.sortable">
                    <template v-if="item.prop == 'createdAt'" #default="scope">
                        <span>{{ formatTime(scope.row.createdAt) }}</span>
                    </template>
                    <template v-if="item.prop == 'channelName'" #default="scope">
                        <span>{{ getChannelTxt(scope.row.channelName) }}</span>
                    </template>
                    <template v-if="item.prop == 'isp'"  #default="scope">
                        <el-text v-if="scope.row.isp == '0'">中国移动</el-text>
                        <el-text v-if="scope.row.isp == '1'">中国联通</el-text>
                        <el-text v-if="scope.row.isp == '2'">中国电信</el-text>
                    </template>
                    <template v-if="item.prop == 'disabled'" #default="scope">
                        <el-switch
                            v-model="scope.row.disabled"
                            :active-value="false"
                            :inactive-value="true"
                            active-color="green"
                            inactive-color="red"
                            @change="disabledChange(scope.row)"
                        />
                    </template>

                </el-table-column>

            </template>
            <el-table-column fixed="right" header-align="center" align="center" label="操作"
                             class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-tooltip content="修改" placement="top">
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                                   v-permission="['sys.config.dict.update']"></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top" v-if="scope.row.path != '0001'">
                        <el-button link type="danger" icon="Delete"
                                   @click="handleDelete(scope.row)"
                                   v-permission="['sys.config.dict.delete']"></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <el-row>
            <pagination :total="queryParams.totalCount" v-model:page="queryParams.pageNo"
                        v-model:limit="queryParams.pageSize" @pagination="list"/>
        </el-row>

        <el-dialog title="新增" v-model="showCreate" width="600px">
            <el-form ref="createRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="选择渠道" prop="cId">
                            <el-select-v2
                                popper-class="link-list-area"
                                v-model="formData.cId"
                                :item-height="50"
                                filterable
                                :props="{
                                    value:'id',
                                    label:'channelId'
                                }"
                                :options="channelOption"
                                placeholder="请输入渠道号"
                            >
                                <template #default="{ item }">
                                    <div class="name">{{ item.channelId }}</div>
                                    <span class="addr">{{ item.link }}</span>
                                </template>
                            </el-select-v2>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="投放地区" prop="areaCode">
                            <el-cascader
                                v-model="formData.areaCode"
                                :options="adverArea"
                                :props="{
                                    multiple: true
                                }"
                                ref="selectedLabels"
                                collapse-tags
                                collapse-tags-tooltip
                                clearable
                                style="width: 100%"
                                @change="handleCascaderChange"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="运营商" prop="isp">
                                    <el-select
                                        v-model="formData.isp"
                                        placeholder="请选择运营商"
                                        size="large"
                                        style="width: 240px"
                                    >
                                        <el-option
                                            v-for="item in ispOption"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item prop="cpId" label="链接类型">
                                    <el-input v-model="formData.cpId" :min="1"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="24">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item prop="adNumber" label="投放量">
                                    <el-input-number v-model="formData.adNumber" :min="1"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item prop="adRatio" label="投放比例">
                                    <el-input-number v-model="formData.adRatio" :min="1"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="24">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item prop="adWarn" label="投放预警量">
                                    <el-input-number v-model="formData.adWarn" :min="1"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item prop="disabled" label="渠道状态">
                                    <el-switch
                                        v-model="formData.disabled"
                                        :active-value="false"
                                        :inactive-value="true"
                                        active-color="green"
                                        inactive-color="red"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="create">确 定</el-button>
                    <el-button @click="showCreate = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog title="修改" v-model="showUpdate" width="40%">
            <el-form ref="updateRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="选择渠道" prop="cId">
                            <el-select-v2
                                popper-class="link-list-area"
                                v-model="formData.cId"
                                :item-height="50"
                                filterable
                                :props="{
                                    value:'id',
                                    label:'channelId'
                                }"
                                :options="channelOption"
                                placeholder="请输入渠道号"
                            >
                                <template #default="{ item }">
                                    <div class="name">{{ item.channelId }}</div>
                                    <span class="addr">{{ item.link }}</span>
                                </template>
                            </el-select-v2>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="投放地区" prop="areaCode">
                            <el-cascader
                                v-model="formData.areaCode"
                                :options="adverArea"
                                :props="{
                                    multiple: true
                                }"
                                collapse-tags
                                collapse-tags-tooltip
                                clearable
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="运营商" prop="isp">
                                    <el-select
                                        v-model="formData.isp"
                                        placeholder="请选择运营商"
                                        size="large"
                                        style="width: 240px"
                                    >
                                        <el-option
                                            v-for="item in ispOption"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item prop="cpId" label="链接类型">
                                    <el-input v-model="formData.cpId" :min="1"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="24">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item prop="adNumber" label="投放量">
                                    <el-input-number v-model="formData.adNumber" :min="1"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item prop="adRatio" label="投放比例">
                                    <el-input-number v-model="formData.adRatio" :min="1"/>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="24">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item prop="adWarn" label="投放预警量">
                                    <el-input-number v-model="formData.adWarn" :min="1"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item prop="disabled" label="渠道状态">
                                    <el-switch
                                        v-model="formData.disabled"
                                        :active-value="false"
                                        :inactive-value="true"
                                        active-color="green"
                                        inactive-color="red"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="update">确 定</el-button>
                    <el-button @click="showUpdate = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>
<script setup lang="ts" name="platform-sys-plat">
import {onMounted, reactive, ref, toRaw} from 'vue'
import modal from '/@/utils/modal'
import {doCreate, doDelete, doDisable, doUpdate, getInfo, getList, reqChannelList} from '/@/api/platform/plat/area'
import {toRefs} from '@vueuse/core'
import {ElForm} from 'element-plus'
import {formatTime} from '/@/utils/common'
import {reqAreaSecond} from "/@/api/platform/sys/area";
import {getChannelTxt} from "/@/utils/channel";

const createRef = ref<InstanceType<typeof ElForm>>()
const updateRef = ref<InstanceType<typeof ElForm>>()
const queryRef = ref<InstanceType<typeof ElForm>>()

const tableData = ref([])
const tableLoading = ref(false)
const showSearch = ref(true)
const showCreate = ref(false)
const showUpdate = ref(false)
const selectedLabels = ref([]);

const data = reactive({
    formData: {
        id: '',
        cId: '',
        areaCode: [],
        areaName: [],
        adNumber: '',
        adRatio: '',
        adWarn: '',
        disabled: '',
    },
    adverArea: [],
    channelOption: [],
    links: [],
    queryParams: {
        pageNo: 1,
        pageSize: 10,
        totalCount: 0,
        pageOrderName: 'createdAt',
        pageOrderBy: 'descending'
    },
    ispOption:[
        {
            value: '0',
            label: '中国移动',
        },
        {
            value: '1',
            label: '中国联通',
        },
        {
            value: '2',
            label: '中国电信',
        }
    ],
    formRules: {
        cId: [{required: true, message: "请选择渠道名称", trigger: "change"}],
        cpId: [{required: true, message: "请输入链接类型", trigger: "change"}],
        isp: [{required: true, message: "请选择运营商", trigger: "blur"}],
        areaCode: [{required: true, message: "请选择投放地区", trigger: "change"}],
        adNumber: [{required: true, message: "请输入投放量", trigger: "blur"}],
        adRatio: [{required: true, message: "请输入投放比例", trigger: "blur"}],
        adWarn: [{required: true, message: "请输入投放预警量", trigger: "blur"}],
    },
})

const {formData, queryParams, formRules, links, adverArea, channelOption,ispOption} = toRefs(data)


const columns = ref([
    {prop: 'id', label: `ID`, show: true, fixed: 'left', width: 200},
    {prop: 'channelId', label: `渠道号`, show: true, fixed: 'left'},
    {prop: 'channelName', label: `渠道名称`, show: true, fixed: 'left'},
    {prop: 'cpId', label: `链接类型`, show: true, fixed: 'left'},
    {prop: 'isp', label: `运营商`, show: true, fixed: 'left'},
    {prop: 'areaName', label: `投放地区`, show: true, fixed: 'left'},
    {prop: 'adNumber', label: `投放量`, show: true, fixed: 'left'},
    {prop: 'adRatio', label: `投放比例`, show: true, fixed: 'left'},
    {prop: 'adWarn', label: `投放预警量`, show: true, fixed: 'left'},
    {prop: 'disabled', label: `上下架`, show: true, fixed: false},
    {prop: 'createdAt', label: `创建时间`, show: true, fixed: false, width: 160}
])


//搜索渠道链接
const handleSearch = () => {
    queryParams.value.pageNo = 1
    list()
}
const resetSearch = () => {
    queryRef.value?.resetFields()
    list()
}
// 查询表格
const list = () => {
    tableLoading.value = true
    getList(queryParams.value).then((res) => {
        tableLoading.value = false
        tableData.value = res.data.list as never
        queryParams.value.totalCount = res.data.totalCount as never
    })
}
// 提交新增
const create = () => {
    if (!createRef.value) return
    createRef.value.validate((valid) => {
        if (valid) {
            doCreate(formData.value).then((res: any) => {
                modal.msgSuccess(res.msg)
                showCreate.value = false
                resetSearch()
            })
        }
    })
}
// 修改按钮
const handleUpdate = (row: any) => {
    getInfo(row.id).then((res: any) => {
        res.data.areaCode=JSON.parse(res.data.areaCode)
        formData.value = res.data
        getChanelOption()
        getAreaSecond()
        showUpdate.value = true
    })
}

// 删除按钮
const handleDelete = (row: any) => {
    modal.confirm('此操作将删除 ' + row.channelName + ' 及其下级，请谨慎操作！').then(() => {
        return doDelete(row.id);
    }).then(() => {
        list()
        modal.msgSuccess('删除成功')
    }).catch(() => {
    })
}
const resetForm = (formEl: InstanceType<typeof ElForm> | undefined) => {
    formData.value = {
        id: '',
        channelId: '',
        channelName: '',
        link: '',
        disabled: false,
    }
    formEl?.resetFields()
}


//获取渠道列表
const getChanelOption = async () => {
    const res = await reqChannelList()
    channelOption.value = res.data || []
}

const getAreaSecond = async () => {
    const res = await reqAreaSecond()
    adverArea.value = res.data || []
}
const getCascaderObj=(path:any,options:any) =>{
    const result = {}
    path.forEach((value, index) => {
        const option = options.find((opt) => {
            console.log(opt)
            return opt.value === value;
        })

        // if (option) {
        //     const key = `level${index + 1}Id`  //这里换成后端约定好的字段Id
        //     const labelKey = `level${index + 1}Name` //这里换成后端约定好的字段Name
        //     result[key] = value
        //     result[labelKey] = option.label
        //     options = option.children // 递归查找下一级选项
        // }
    })
    return result
}
const handleCascaderChange = (value:any) => {
};

const handleCreate = (row: any) => {
    resetForm(createRef.value)
    showCreate.value = true
    getChanelOption()
    getAreaSecond()
}
// 启用禁用
const disabledChange = (row: any) => {
    doDisable({disabled: row.disabled, id: row.id}).then((res: any) => {
        modal.msgSuccess(res.msg)
        list()
    }).catch(() => {
        setTimeout(() => {
            row.disabled = !row.disabled
        }, 300)
    })
}
// 提交修改
const update = () => {
    if (!updateRef.value) return
    updateRef.value.validate((valid) => {
        if (valid) {
            doUpdate(formData.value).then((res: any) => {
                modal.msgSuccess(res.msg)
                showUpdate.value = false
                resetSearch()
            })
        }
    })
}
onMounted(() => {
    list()
})
</script>
<!--定义布局-->
<route lang="yaml">
meta:
    layout: platform/index
</route>
<style scoped>
.time {
    font-size: 11px;
    background-color: rgb(135, 208, 104);
    color: #fff;
    display: inline-block;
    width: 38px;
    border-radius: 2px;
    padding-left: 1px;
    height: 22px;
}

.content {
    white-space: normal;
    word-break: break-all;
}

</style>
<style>
.link-list-area {
    li {
        line-height: normal;
        padding: 7px;

        .name {
            text-overflow: ellipsis;
            overflow: hidden;
        }

        .addr {
            font-size: 12px;
            color: #b4b4b4;
        }

        .highlighted .addr {
            color: #ddd;
        }
    }
}
.areaName-row {
    white-space: pre-line;
    padding-left: 20px;
}
</style>
